package ar.com.ford.it.fullEconomics.logic;

import java.sql.Timestamp;
import java.util.Collection;
import org.apache.commons.lang.StringUtils;
import ar.com.ford.it.fullEconomics.FullEconomicsPrs;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.persistence.dao.CommodityDao;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp02Commodity;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;

public class CommodityLogic {
    private static final String CLASS_NAME = CommodityLogic.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);


    /**
     * Obtiene los commodities por nombre
     * 
     * @param name
     * @param plant
     * @return
     */
    public Teesp02Commodity findCommodityByName(String name, Teesg01Plant plant)
            throws FullEconomicsException {

        String METHOD_NAME = "findCommodityByName";
        log.entering(CLASS_NAME, METHOD_NAME);

        Teesp02Commodity result = new Teesp02Commodity();
        Teesp02Commodity comm = new Teesp02Commodity();
        CommodityDao dao = new CommodityDao();
        try {
            comm.setEesp02CommodityNameN(name);
            comm.setEesp02PlantCodeC(plant);
            comm.setEesp02CommodityNumberK(null);
            result = dao.findCommodityByName(comm);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find Commodity By Name Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Commodity.FINDBYCODE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);

        return result;
    }
    /**
     * Obtiene los commodities por nombre
     * 
     * @param name
     * @param plant
     * @return
     */
    public Teesp02Commodity findCommodityByCode(String code, Teesg01Plant plant)
            throws FullEconomicsException {

        String METHOD_NAME = "findCommodityByName";
        log.entering(CLASS_NAME, METHOD_NAME);

        Teesp02Commodity result = new Teesp02Commodity();
        Teesp02Commodity comm = new Teesp02Commodity();
        CommodityDao dao = new CommodityDao();
        Integer intCode = new Integer(code);
        try {
            comm.setEesp02CommodityNumberK(intCode);
            comm.setEesp02PlantCodeC(plant);
            result = (Teesp02Commodity) dao.getObjById(comm);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find Commodity By Name Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Commodity.FINDBYCODE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);

        return result;
    } 

    /**
     * Busca Commoditys segun code, name y en determinada planta
     * 
     * @param code
     * @return Commoditys que se correspondan con la busqueda.
     */
    public Collection<Teesp02Commodity> findCommodities(String code,
                                                       String name,
                                                       Teesg01Plant plant)
            throws FullEconomicsException {

        String METHOD_NAME = "findCommodities";
        log.entering(CLASS_NAME, METHOD_NAME);

        CommodityDao dao = new CommodityDao();
        Teesp02Commodity commodity = new Teesp02Commodity();
        Collection<Teesp02Commodity> ret = null;

        commodity.setEesp02PlantCodeC(plant);
        if (StringUtils.isBlank(code)) {
            commodity.setEesp02CommodityNumberK(null);
        } else {
            commodity.setEesp02CommodityNumberK(new Integer(code));
        }
        if (StringUtils.isBlank(name)) {
            commodity.setEesp02CommodityNameN(null);
        } else {
            commodity.setEesp02CommodityNameN(name);
        }

        try {
            ret = dao.findCommodities(commodity);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find Commoditys Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Commodity.FINDALL);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);

        return ret;
    }

    /**
     * Busca Commoditys segun sus partes
     * 
     * @param prefix
     * @param base
     * @param suffix
     * @param plant
     * @return Commoditys que se correspondan con la busqueda.
     */
    public Collection<Teesp02Commodity> findCommoditiesByParts(String prefix,
                                                       String base,
                                                       String suffix,
                                                       Teesg01Plant plant)
            throws FullEconomicsException {

        String METHOD_NAME = "findCommoditiesByParts";
        log.entering(CLASS_NAME, METHOD_NAME);

        CommodityDao dao = new CommodityDao();
        Teesp01Part part = new Teesp01Part();
        Collection<Teesp02Commodity> ret = null;

        part.setEesp01PlantCodeC(plant);
        if (StringUtils.isBlank(prefix)) {
            part.setEesp01PartPrefixCodeC(null);
        } else {
            part.setEesp01PartPrefixCodeC(prefix);
        }
        if (StringUtils.isBlank(base)) {
            part.setEesp01PartBaseCodeC(null);
        } else {
            part.setEesp01PartBaseCodeC(base);
        }
        if (StringUtils.isBlank(suffix)) {
            part.setEesp01PartSuffixCodeC(null);
        } else {
            part.setEesp01PartSuffixCodeC(suffix);
        }

        try {
            ret = dao.findCommoditiesByParts(part);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find Commoditys Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Commodity.FINDALL);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);

        return ret;
    }
    /**
     * Da de alta el Commodity pasado por parametro
     * 
     * @param commodity
     * Commodity a dar de alta
     * @param user
     * Usuario que da de alta el Commodity
     */
    public void createCommodity(Teesp02Commodity commodity,
                                FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "createCommodity";
        log.entering(CLASS_NAME, METHOD_NAME);

        CommodityDao dao = new CommodityDao();
        String[] fields = new String[1];
        Object[] values = new Object[1];

        try {
            PersistenceUtil.newTransaction();
            fields[0] = "eesp02PlantCodeC";
            values[0] = user.getTeesg01Plant();
            Integer lastCode = dao.getMax(new Teesp02Commodity(), fields,
                    values, "eesp02CommodityNumberK");
            commodity.setEesp02PlantCodeC(user.getTeesg01Plant());
            commodity.setEesp02CommodityNumberK(lastCode + 1);
            commodity.setEesp02CreateUserC(user.getId());
            commodity.setEesp02LastUpdtUserC(user.getId());
            commodity
                    .setEesp02CreateS(new Timestamp(System.currentTimeMillis()));
            commodity.setEesp02LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));

            dao.createCommodity(commodity);
            PersistenceUtil.commitTransaction();

        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Create Commodity Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.Commodity.CREATE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Actualiza el Commodity pasado por parametro
     * 
     * @param commodity
     * Commodity a actualizar
     * @param user
     * Usuario que actualiza el Commodity
     */
    public void updateCommodity(Teesp02Commodity commodity,
                                FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "updateCommodity";
        log.entering(CLASS_NAME, METHOD_NAME);

        CommodityDao dao = new CommodityDao();

        Teesp02Commodity workingCopy = null;

        try {
            PersistenceUtil.newTransaction();

            // XXX Ver si esta bien llamar este clearCache aca
            PersistenceUtil.getPersistenceManager().clearCache();

            workingCopy = dao.getCommodityForUpdate(commodity
                    .getEesp02CommodityNumberK(), user.getTeesg01Plant());
            workingCopy.setEesp02LastUpdtUserC(user.getId());
            workingCopy.setEesp02LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));

            // Campos modificados, in y out date
            workingCopy.setEesp02CommodityInDateY(commodity
                    .getEesp02CommodityInDateY());
            workingCopy.setEesp02CommodityOutDateY(commodity
                    .getEesp02CommodityOutDateY());
            workingCopy.setEesp02CommodityNameN(commodity
                    .getEesp02CommodityNameN());
            PersistenceUtil.commitTransaction();

        } catch (PersistenceException pe) {

            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Update Commodity Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.Commodity.UPDATE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Elimina el commodity pasado por parametro
     * 
     * @param commodity
     * Commodity a eliminar
     */
    public void deleteCommodity(Teesp02Commodity commodity)
            throws FullEconomicsException {

        String METHOD_NAME = "deleteCommodity";
        log.entering(CLASS_NAME, METHOD_NAME);

        try {
            PersistenceUtil.newTransaction();

            CommodityDao dao = new CommodityDao();

            dao.deleteCommodity(commodity);
            PersistenceUtil.commitTransaction();

        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Delete Commodity Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.Commodity.DELETE);

        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * devuelve los elementos asosiados al commodity
     * 
     * @param commodity
     * Commodity a eliminar
     */
    public String[] commoditysRelatedElements(Teesp02Commodity commodity)
            throws FullEconomicsException {

        String METHOD_NAME = "commoditysRelatedElements";
        log.entering(CLASS_NAME, METHOD_NAME);

        String[] commRelatedElementsIDs;

        try {
            PersistenceUtil.newTransaction();

            CommodityDao dao = new CommodityDao();

            commRelatedElementsIDs = dao.commodityRelatedElements(commodity);
            PersistenceUtil.commitTransaction();

        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Delete Commodity Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.Commodity.DELETE);

        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return commRelatedElementsIDs;
    }

}
